package com.siwei.mes.service.laboratory.factory.material.fine;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.fineAggregate.FineAggregateHnl;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.fineAggregate.DataFineAggregateHnl;
import com.siwei.mes.entity.laboratory.fineAggregate.DataFineAggregateYjlf;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.DataDefUcLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.FineLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.UploadLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import com.siwei.mes.service.laboratory.factory.material.MaterialLaboratoryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 细骨料-含泥量
 *
 * @Description: 细骨料-含泥量
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/29 21:41
 */
@Service
public class FineHnlFactory extends LaboratoryAbstractService implements MaterialLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Resource
    private UploadLaboratoryMapper uploadLaboratoryMapper;
    @Resource
    private FineLaboratoryMapper fineLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private DataDefUcLaboratoryMapper dataDefUcLaboratoryMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_HNL;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectInfo> testProjectInfoList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail, String samId) {
        log.info("开始上传到协会数据库：【细骨料-{}】", testProjectEnum.getName());
        //将json转成对象
        FineAggregateHnl fineNnl = objJson.toJavaObject(FineAggregateHnl.class);
        if (fineNnl == null) {
            log.info("细骨料-【{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }
        /**判断材料名称是天然砂还是机制砂 对应不同的表**/
        List<String> materialsNameList = Arrays.asList("混合砂", "机制砂", "人工砂");
        if (materialsNameList.contains(experiment.getMaterialsName())) {
            DataFineAggregateYjlf dataFineNnl = new DataFineAggregateYjlf();
            dataFineNnl.setS1("标准法");
            FineAggregateHnl.SyjgInfo syjgInfo = fineNnl.getSyjgInfo();
            if (syjgInfo == null) {
                syjgInfo = new FineAggregateHnl.SyjgInfo();
            }
            dataFineNnl.setS2(NullUtils.ifNull(syjgInfo.getSyzl()));
            dataFineNnl.setS3(NullUtils.ifNull(fineNnl.getJryjlryzl()));
            dataFineNnl.setS4(NullUtils.ifNull(syjgInfo.getMbz()));
            dataFineNnl.setS5(NullUtils.ifNull(syjgInfo.getJryjlrytj1()));
            dataFineNnl.setS6(NullUtils.ifNull(syjgInfo.getJryjlrytj2()));
            dataFineNnl.setS7(NullUtils.ifNull(syjgInfo.getJryjlrytj3()));
            dataFineNnl.setS8(NullUtils.ifNull(syjgInfo.getJryjlrytj4()));
            dataFineNnl.setS9(NullUtils.ifNull(syjgInfo.getJryjlrytj5()));
            dataFineNnl.setS10(NullUtils.ifNull(syjgInfo.getJryjlrytj6()));
            dataFineNnl.setS11(NullUtils.ifNull(syjgInfo.getJryjlrytj7()));
            dataFineNnl.setS12(NullUtils.ifNull(syjgInfo.getJryjlrytj8()));
            //TODO 缺少两个 溶液加入量 9 10 品控对应没有字段 协会未看到赋值
            dataFineNnl.setS15(NullUtils.ifNull(syjgInfo.getSycxsj1()));
            dataFineNnl.setS16(NullUtils.ifNull(syjgInfo.getSycxsj2()));
            dataFineNnl.setS17(NullUtils.ifNull(syjgInfo.getSycxsj3()));
            dataFineNnl.setS18(NullUtils.ifNull(syjgInfo.getSycxsj4()));
            dataFineNnl.setS19(NullUtils.ifNull(syjgInfo.getSycxsj5()));
            dataFineNnl.setS20(NullUtils.ifNull(syjgInfo.getSycxsj6()));
            dataFineNnl.setS21(NullUtils.ifNull(syjgInfo.getSycxsj7()));
            dataFineNnl.setS22(NullUtils.ifNull(syjgInfo.getSycxsj8()));
            dataFineNnl.setS25(NullUtils.ifNull(fineNnl.getSycxsj1()));
            dataFineNnl.setS26(NullUtils.ifNull(syjgInfo.getDxjl()));

            dataFineNnl.setS33(NullUtils.ifNull(fineNnl.getHnlpjz()));

            List<FineAggregateHnl.HnljzsInfo> hnljzsInfo = fineNnl.getHnljzsInfo();
            if (CollectionUtil.isNotEmpty(hnljzsInfo)) {
                if (!hnljzsInfo.isEmpty()) {
                    FineAggregateHnl.HnljzsInfo hnljzsInfoOne = hnljzsInfo.get(0);
                    dataFineNnl.setS27(NullUtils.ifNull(hnljzsInfoOne.getHqsyzl()));
                    dataFineNnl.setS28(NullUtils.ifNull(hnljzsInfoOne.getHhsyzl()));
                    dataFineNnl.setS29(NullUtils.ifNull(hnljzsInfoOne.getSfhl()));
                }
                if (hnljzsInfo.size() > 1) {
                    FineAggregateHnl.HnljzsInfo hnljzsInfoTwo = hnljzsInfo.get(1);
                    dataFineNnl.setS30(NullUtils.ifNull(hnljzsInfoTwo.getHqsyzl()));
                    dataFineNnl.setS31(NullUtils.ifNull(hnljzsInfoTwo.getHhsyzl()));
                    dataFineNnl.setS32(NullUtils.ifNull(hnljzsInfoTwo.getHnl()));
                }
            }

            //设置公共属性
            super.setCommonProperties(sampleNo, experiment, dataFineNnl, "骨料检测室", fineNnl.getJcrq(), detail);

            //根据样品编码查询细骨料含泥量
            Map<String, Object> data_jgcl_ss_rgsjhhszsfhl_yjlfBySampleNo = fineLaboratoryMapper.findDATA_JGCL_SS_RGSJHHSZSFHL_YJLFBySampleNo(sampleNo);
            //查询没值说明需要  新增细骨料含泥量
            if (data_jgcl_ss_rgsjhhszsfhl_yjlfBySampleNo == null) {
                fineLaboratoryMapper.addDDATA_JGCL_SS_RGSJHHSZSFHL_YJLF(dataFineNnl);
            } else {
                //修改细骨料含泥量
                fineLaboratoryMapper.updateDATA_JGCL_SS_RGSJHHSZSFHL_YJLF(dataFineNnl);
            }
        } else {
            DataFineAggregateHnl dataFineNnl = new DataFineAggregateHnl();
            dataFineNnl.setS7(NullUtils.ifNull(fineNnl.getHnlpjz()));

            List<FineAggregateHnl.HnljzsInfo> hnljzsInfo = fineNnl.getHnljzsInfo();
            if (CollectionUtil.isNotEmpty(hnljzsInfo)) {
                if (!hnljzsInfo.isEmpty()) {
                    FineAggregateHnl.HnljzsInfo hnljzsInfoOne = hnljzsInfo.get(0);
                    dataFineNnl.setS1(NullUtils.ifNull(hnljzsInfoOne.getHqsyzl()));
                    dataFineNnl.setS2(NullUtils.ifNull(hnljzsInfoOne.getHhsyzl()));
                    dataFineNnl.setS3(NullUtils.ifNull(hnljzsInfoOne.getHnl()));
                }
                if (hnljzsInfo.size() > 1) {
                    FineAggregateHnl.HnljzsInfo hnljzsInfoTwo = hnljzsInfo.get(1);
                    dataFineNnl.setS4(NullUtils.ifNull(hnljzsInfoTwo.getHqsyzl()));
                    dataFineNnl.setS5(NullUtils.ifNull(hnljzsInfoTwo.getHhsyzl()));
                    dataFineNnl.setS6(NullUtils.ifNull(hnljzsInfoTwo.getHnl()));
                }
            }

            //设置公共属性
            super.setCommonProperties(sampleNo, experiment, dataFineNnl, "骨料检测室", fineNnl.getJcrq(), detail);

            //根据样品编码查询细骨料含泥量
            Map<String, Object> data_jgcl_ss_szhnlBySampleNo = fineLaboratoryMapper.findDATA_JGCL_SS_SZHNLBySampleNo(sampleNo);
            //查询没值说明需要  新增细骨料含泥量
            if (data_jgcl_ss_szhnlBySampleNo == null) {
                fineLaboratoryMapper.addDATA_JGCL_SS_SZHNL(dataFineNnl);
            } else {
                //修改细骨料含泥量
                fineLaboratoryMapper.updateDATA_JGCL_SS_SZHNL(dataFineNnl);
            }
        }

        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();

        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
            if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }

        for (String str : set) {
            DataDefaultUc defaultUc = new DataDefaultUc();

            Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

            if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                continue;
            }
            String parameterID = itemParameter.get("ParameterID").toString();

            String jcrq = fineNnl.getJcrq();

            if(fineNnl.getSyjgInfo() != null){
                defaultUc.setConclusion(fineNnl.getSyjgInfo().getDxjl());
                defaultUc.setUcResultValue(fineNnl.getSyjgInfo().getDxjl());
            }



            if(itemParameter.get("ParameterName") != null && ("亚甲蓝试验").equals(itemParameter.get("ParameterName")) || ("亚甲蓝值").equals(itemParameter.get("ParameterName"))){
                if(fineNnl != null && fineNnl.getSyjgInfo() != null && fineNnl.getSyjgInfo().getMbz() != null){
                    defaultUc.setUcTestValue(fineNnl.getSyjgInfo().getMbz());
                    //亚甲蓝单位写死g/kg
                    defaultUc.setUcUnit("g/kg");
                }
            }else {
                defaultUc.setUcTestValue(fineNnl.getHnlpjz());

                //获取标准值
                for (CheckBatchConfig projectInfo : batchConfigList) {
                    if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_HNL.getCode())) {
                        defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
                    }
                }
            }

            //根据物料信息设置判断配置
            for (TestProjectSpecConfig test : testProjectSpecConfigList) {
                if (TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_HNL.getCode().equals(test.getTestProjectCode())) {
                    if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                        String json = test.getObjJson();
                        super.setUcStandardValue(defaultUc, json, "hnl");
                    }
                }
            }

            //赋值
            super.setDefUc(defaultUc, experiment, "骨料检测室", sampleNo, jcrq, detail);

            defaultUc.setUcParameterID(parameterID);//项目id

            //新增或修改DataDefaultUc
            super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
        }
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap, String samId, List<TestProjectInfo> testProjectInfoList) {
        log.info("开始下载协数据到品控：【细骨料-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        //将json转成对象
        FineAggregateHnl fineAggregateHnl = objJson.toJavaObject(FineAggregateHnl.class);
        if (fineAggregateHnl == null) {
            log.info("细骨料-【{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }
        Map<String, Object> data;
        List<String> materialsNameList = Arrays.asList("混合砂", "机制砂", "人工砂");
        if (materialsNameList.contains(experiment.getMaterialsName())) {
            data = fineLaboratoryMapper.findDATA_JGCL_SS_RGSJHHSZSFHL_YJLFBySampleNo(sampleNo);
        }else{
            data = fineLaboratoryMapper.findDATA_JGCL_SS_SZHNLBySampleNo(sampleNo);
        }
        if (data == null) {
            log.info("根据样品编码查询细骨料含泥量为空，跳过下载！sampleNo：{}", sampleNo);
            return null;
        }
        if (materialsNameList.contains(experiment.getMaterialsName())) {
            FineAggregateHnl.setValueYjl(fineAggregateHnl, data);
        } else {
            FineAggregateHnl.setValueHnl(fineAggregateHnl, data);
        }
        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();
        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
            if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }
        for (String str : set) {

            Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

            if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                continue;
            }
            String parameterID = itemParameter.get("ParameterID").toString();

            //查询data_defalutUc 是否存在
            Map<String, Object> uCdata = dataDefUcLaboratoryMapper.findDATA_DefaultUCBySampleNo(sampleNo, parameterID);
            if (uCdata == null) {
                continue;
            }
            if (uCdata.get("Conclusion") != null) {
                fineAggregateHnl.setDxjl(uCdata.get("Conclusion").toString());
            }
        }
        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(fineAggregateHnl);
        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data.get("Equipment")));
        detail.setTemperature(NullUtils.ifNull(data.get("Temperature")));
        detail.setHumidness(NullUtils.ifNull(data.get("Humidity")));
        detail.setExperimentGist(NullUtils.ifNull(data.get("DetectonRuleCode")));
        detail.setJudgeGist(NullUtils.ifNull(data.get("AccessRuleCode")));

        experimentDetailMapper.updateByPrimaryKeySelective(detail);
        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}
